'use strict';

const uniIdCommon = require('uni-id-common')

exports.main = async (event, context) => {
  console.log('处理退款审批云函数被调用，参数:', event)
  
  // 管理员访问检查
  const isAdminAccess = event.isAdmin || false
  let uid = null
  
  if (!isAdminAccess) {
    const token = context.uniIdToken || event.uniIdToken || (event.args && event.args.uniIdToken)
    if (!token) {
      return { code: 401, msg: '未登录' }
    }
    
    const uniId = uniIdCommon.createInstance({ context })
    const tokenRes = await uniId.checkToken(token)
    if (tokenRes.code !== 0) {
      return { code: 401, msg: 'token无效或已过期' }
    }
    
    // 检查是否是管理员
    const userInfo = tokenRes.userInfo
    if (!userInfo || userInfo.role !== 'admin') {
      return { code: 403, msg: '无权操作，仅限管理员' }
    }
    
    uid = tokenRes.uid
  } else {
    console.log('管理员访问，跳过token验证')
    uid = 'admin'
  }

  const { refundId, action, remark } = event
  
  if (!refundId || !action) {
    return { code: 400, msg: '参数不完整' }
  }
  
  if (!['approve', 'reject', 'complete'].includes(action)) {
    return { code: 400, msg: '不支持的操作类型' }
  }

  const db = uniCloud.database()
  const timestamp = Date.now()
  
  try {
    console.log(`开始处理退款审批 - 退款ID: ${refundId}, 操作: ${action}`)
    
    // 获取退款记录
    const refundResult = await db.collection('refund_records').doc(refundId).get()
    if (!refundResult.data || refundResult.data.length === 0) {
      return { code: 404, msg: '退款记录不存在' }
    }
    
    const refund = refundResult.data[0]
    console.log('找到退款记录:', refund)
    
    // 检查退款状态
    if (action === 'complete' && refund.status !== 'approved') {
      return { code: 400, msg: '只能处理已批准的退款申请' }
    }
    
    if ((action === 'approve' || action === 'reject') && refund.status !== 'pending') {
      return { code: 400, msg: '该退款申请已处理，无法重复操作' }
    }
    
    // 根据操作类型更新退款记录
    let updateData = {
      update_time: timestamp
    }
    
    let resultMessage = ''
    
    if (action === 'approve') {
      updateData.status = 'approved'
      updateData.auditor_id = uid
      updateData.auditor_name = '管理员'
      updateData.audit_time = timestamp
      updateData.audit_remark = remark || ''
      updateData.progress = 3
      resultMessage = '退款申请已批准'
      
      console.log('退款已批准，准备处理退款...')
      
    } else if (action === 'reject') {
      updateData.status = 'rejected'
      updateData.auditor_id = uid
      updateData.auditor_name = '管理员'
      updateData.audit_time = timestamp
      updateData.audit_remark = remark || ''
      updateData.progress = 1
      resultMessage = '退款申请已拒绝'
      
      console.log('退款已拒绝，原因:', remark)
      
    } else if (action === 'complete') {
      updateData.status = 'completed'
      updateData.complete_time = timestamp
      updateData.progress = 4
      resultMessage = '退款处理完成'
      
      console.log('退款已完成')
      // TODO: 调用真实的支付系统退款API
    }
    
    // 更新退款记录
    await db.collection('refund_records').doc(refundId).update(updateData)
    
    console.log('退款审批完成:', resultMessage)
    
    // 发送系统通知给申请人
    try {
      await sendRefundNotification(refund, action, resultMessage, remark)
    } catch (notifyError) {
      console.error('发送通知失败:', notifyError)
      // 不影响主流程
    }
    
    return {
      code: 200,
      msg: resultMessage,
      data: {
        refundId: refundId,
        action: action,
        status: updateData.status,
        timestamp: timestamp
      }
    }
    
  } catch (error) {
    console.error('处理退款审批失败:', error)
    return {
      code: 500,
      msg: '处理失败: ' + error.message,
      error: error.toString()
    }
  }
}

// 发送退款通知
async function sendRefundNotification(refund, action, resultMessage, remark) {
  console.log(`发送退款通知 - 退款ID: ${refund._id}, 操作: ${action}`)
  
  const db = uniCloud.database()
  
  try {
    // 构建通知内容
    let content = `您的退款申请已${action === 'approve' ? '批准' : '拒绝'}。`
    if (remark) {
      content += ` 备注：${remark}`
    }
    
    const notification = {
      user_id: refund.user_id,
      type: 'refund_status',
      category: 'financial',
      title: '退款审核结果',
      content: content,
      related_id: refund._id,
      related_type: 'refund',
      priority: 'high',
      action_url: `/pages/order/detail?id=${refund.task_id}`,
      action_text: '查看订单',
      create_time: new Date()
    }
    
    await db.collection('notification-messages').add(notification)
    console.log(`退款通知已发送给用户: ${refund.user_id}`)
    
  } catch (error) {
    console.error('发送退款通知失败:', error)
    throw error
  }
}

